package com.xf.controller;

import com.xf.common.core.entity.FebsResponse;
import com.xf.common.core.entity.QueryRequest;
import cc.mrbird.febs.common.datasource.starter.tenant.Tenant;
import com.xf.common.core.exception.FebsException;
import com.xf.common.core.utils.FebsUtil;
import com.xf.service.TenantService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * 业务空间模块
 *
 * @author xufeng
 * @version 1.0
 * @date 2021/10/20
 */
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("workspace")
public class WorkspaceController {
    @Autowired
    private TenantService tenantService;



    @GetMapping
    @PreAuthorize("hasAuthority('client:view')")
    public FebsResponse list(QueryRequest request, Tenant tenant) {
        Map<String, Object> dataTable = FebsUtil.getDataTable(tenantService.getPage(request, tenant));
        return new FebsResponse().data(dataTable);
    }

    /**
     * 创建工作空间
     * @param tenant
     * @return
     */
    @PostMapping("/create")
    public FebsResponse createWorkspace(@Valid Tenant tenant) {
        tenantService.create(tenant);
        return new FebsResponse();

    }

    /**
     * 修改工作空间信息
     * @param tenant
     * @return
     */
    @PutMapping("/update")
    public FebsResponse updateWorkspace(@Valid Tenant tenant) {
        //验证开始
        if(!"admin".equals(FebsUtil.getCurrentUsername())){
            throw new FebsException("非admin用户无法修改工作空间");
        }
        boolean flag = tenantService.updateById(tenant);
        return new FebsResponse();

    }

    /**
     * 删除工作空间信息
     * @param  tenantId 工作空间id
     * @return
     */
    @DeleteMapping("/del")
    public FebsResponse updateWorkspace(@RequestParam("tenantId") String tenantId) {
        //验证开始
        if(!"admin".equals(FebsUtil.getCurrentUsername())){
            throw new FebsException("非admin用户无法删除工作空间");
        }
        boolean flag = tenantService.removeById(tenantId);
        return new FebsResponse();

    }

}
